//
//  Home.swift
//  AnimatedHeader
//
//  Created by alanzhangg on 2023/5/13.
//

import SwiftUI

struct Home: View {
    
    @StateObject var headerViewModel = HeaderViewModel()
    
    //disabling bouncing..
    
    init() {
        UIScrollView.appearance().bounces = false
    }
    
    var body: some View {
        ZStack(alignment: .top) {
            //header view...
            HeaderView()
                .zIndex(1)
                .offset(y: headerViewModel.headerOffset)
            //view
            
            ScrollView(.vertical, showsIndicators: false) {
                VStack(spacing: 15){
                    ForEach(1...4, id: \.self) { index in
                        Image("IMG_\(index)")
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: rect.width - 30, height: 250)
                            .cornerRadius(1)
                        
                        HStack(spacing: 10){
                            Image("youtube")
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .frame(width: 35, height: 35)
                                .clipShape(Circle())
                            
                            VStack(alignment: .leading, spacing: 4){
                                
                                Text("new sony camera unboxing and reviews")
                                    .fontWeight(.bold)
                                    .foregroundColor(.primary)
                                    .lineLimit(2)
                                    .multilineTextAlignment(.leading)
                                
                                Text("iJustine. 4 hours ago")
                                    .font(.caption)
                                    .foregroundColor(.gray)
                                    
                                
                            }
                            
                        }
                        .padding(.bottom, 10)
                    }
                }
                .padding(.top, 70)
                .overlay(alignment:.top) {
                    //Geometry Reader for getting offset values/
                    GeometryReader { proxy -> Color in
                        
                        let minY = proxy.frame(in: .global).minY
                        
                        DispatchQueue.main.async {
                            if headerViewModel.startMinY == 0{
                                headerViewModel.startMinY = minY
                            }
                            // getting exact offset value by subtracting current from start
                            let offset = headerViewModel.startMinY - minY
                            //getting scroll direction
                            if offset > headerViewModel.offset{
                                
                                //hidding header view
                                //clearing bottom offset
                                headerViewModel.bottomScrollOffset = 0
                                
                                if headerViewModel.topScrollOffset == 0{
                                    headerViewModel.topScrollOffset = offset
                                }
                                let process = headerViewModel.topScrollOffset + getMaxOffset() - offset
                                
                                let offsetCondition = (headerViewModel.topScrollOffset + getMaxOffset()) >= getMaxOffset() && getMaxOffset() - process <= getMaxOffset()
                                let headerOffset =  offsetCondition ? -(getMaxOffset() - process) : -getMaxOffset()
                                headerViewModel.headerOffset = headerOffset
                                
                                
                            }
                            
                            if offset < headerViewModel.offset{
                                
                                //showing header view
                                //clearing topscrollvalue and setting bottom...
                                if headerViewModel.bottomScrollOffset == 0{
                                    headerViewModel.bottomScrollOffset = offset
                                }
                                
                                withAnimation(.easeOut(duration: 0.25)) {
                                    let headerOffset = headerViewModel.headerOffset
                                    
                                    headerViewModel.headerOffset =  headerViewModel.bottomScrollOffset > offset + 40 ? 0 : (headerOffset != -getMaxOffset() ? 0 : headerOffset)
                                }
                                
                                
                            }
                            headerViewModel.offset = offset
                        }
                        
                        
                        
                        return Color.clear
                    }
                    .frame(height: 0)
                }
                
            }
        }
    }
    
    //getting max top offset including top safe area...
    
    func getMaxOffset() -> CGFloat{
        return headerViewModel.startMinY + (edges?.top ?? 0) + 10
    }
    
}

struct Home_Previews: PreviewProvider {
    static var previews: some View {
        Home()
    }
}

var edges = UIApplication.shared.windows.first?.safeAreaInsets
var rect = UIScreen.main.bounds

struct HeaderView: View{
    
    //for dark mode adaption.
    
    @Environment(\.colorScheme) var scheme
    
    var body: some View{
        HStack(spacing: 10){
            
            Image("youtube")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 40, height: 40)
            
            Text("YouTuBe")
                .font(.title)
                .fontWeight(.bold)
                .foregroundColor(.primary)
                .kerning(0.5)
                .offset(x:-10)
            
            
            Spacer()
            
            Button {
                
            } label: {
                Image(systemName: "display")
                    .font(.title2)
                    .foregroundColor(.primary)
            }
            
            Button {
                
            } label: {
                Image(systemName: "bell")
                    .font(.title2)
                    .foregroundColor(.primary)
            }
            
            Button {
                
            } label: {
                Image(systemName: "magnifyingglass")
                    .font(.title2)
                    .foregroundColor(.primary)
            }

            Button {
                
            } label: {
                Image("youtube")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 30, height: 30)
                    .clipShape(Circle())
            }
            
        }
        .padding(.horizontal)
        .padding(.vertical, 8)
        .background(scheme == .dark ? Color.black : Color.white)
        .overlay(alignment: .bottom) {
            Divider()
        }
    }
}
